﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
// Copyright (C) 2021 kingerrobot
// 版权所有。 
//
// 文件名：WarehousingImpl
// 文件功能描述：
//
// 创建者：名字 (zzl)
// 时间：2021/12/14 15:13:13
//
// 修改人：
// 时间：
// 修改说明：
// 版本：V1.0.0
//----------------------------------------------------------------*/
#endregion


using K8.LSF;
using KingerRobot.MexicoSailunMDC.Dao;
using KingerRobot.MexicoSailunWMS.Spi;
using KingerRobot.MexicoSailunWMS.SpiService.Services;
using System.Collections.Generic;

namespace KingerRobot.MexicoSailunWMS.SpiService;
//WMS.OutOrder
public class BOutOrderImpl : IOutOrderService
{
    private readonly static IRcsLocation _RcsLocation = new BRcsLocation();
    private readonly static IWcsLocSku _WcsLocSku = new BWcsLocSku();
    private readonly static IProdSku _ProdSku = new BProdSku();
    private readonly static IProdMaterial _ProdMaterial = new BProdMaterial();
    private readonly static ITaskCmd _TaskCmd = new BTaskCmd();
    private readonly static IWcsEquipLocHold _WcsEquipLocHold = new BWcsEquipLocHold();
    private readonly static IWcsNetAbnormal _WcsNetAbnormal = new BWcsNetAbnormal();
    private readonly static IWmsOutOrderSummary _WmsOutOrderSummary = new BWmsOutOrderSummary();
    private readonly static IWmsOutOrderMaster _WmsOutOrderMaster = new BWmsOutOrderMaster();
    private readonly static IWcsAsrsCrnOutPut _WcsAsrsCrnOutPut = new BWcsAsrsCrnOutPut();
    private readonly static ITask _Task = new BTask();
    private readonly static IWmsSetting _WmsSetting = new BWmsSetting();
    private readonly static IWcsAsrsCrnAbnormalOutPut _WcsAsrsCrnAbnormalOutPut = new BWcsAsrsCrnAbnormalOutPut();
    private readonly static IBakWcsTask _BakWcsTask = new BBakWcsTask();
    private readonly static IMesCuringRequestMaterial _MesCuringRequestMaterial = new BMesCuringRequestMaterial();

    [Obsolete("暂未启用", true)]
    public string CreateOutOrder(CreateOrderParm order)
    {
        var loc = order.loc;
        if (loc == 0)
        {
            return "未找到库位";
        }
        var locInfo = _RcsLocation.GetLocationById(loc);
        //未查询到货位信息
        if (locInfo == null)
        {
            return "未找到库位";
        }
        if (locInfo.LocHasSku != 1)
        {
            return "该库位没有库存";
        }

        //查询库位是否存在SKU
        var locSku = _WcsLocSku.GetWcsLocSkuByLocId(loc);
        if (locSku == null)
        {
            return "未找到相应的SKU信息";
        }
        var prodSku = _ProdSku.GetProdSkuById(locSku.SkuId);
        if (prodSku == null)
        {
            return "未找到相应的SKU信息";
        }

        //验证当前库位是否存在待执行或者执行中的指令
        var locCmd = _TaskCmd.GetExecutableTaskCmdIdkByLocId(loc);
        if (locCmd != 0)
        {
            return "该库位存在正在执行的指令";
        }
        var equip = _WcsEquipLocHold.GetEquipLocHolds().Where(t => t.LocId == loc).FirstOrDefault();
        if (equip == null)
        {
            return "未找到该库位的堆垛机信息";
        }
        //获取异常库位信息
        var tagertLocId = _WcsNetAbnormal.GetAbnormalIdByStartLoc(equip.EquipId.GetValueOrDefault());
        if (tagertLocId == 0)
        {
            return "未找到该库位的异常库位信息";
        }
        var summaryNum = _WmsOutOrderSummary.GetOrderSummaryList().Where(t => t.StartLoc == loc).Count();
        if (summaryNum > 0)
        {
            return "该库位已创建出库单";
        }
        //下面是创建订单主表和明细表数据
        var masterId = _WmsOutOrderMaster.AddOutOrderMaster((int)EnumCodeOutOrderType.WarehouseLocation);
        if (masterId == 0)
        {
            return "创建失败";
        }
        var OutOrderSummary = new POWmsOutOrderSummary
        {
            MasterId = masterId,
            SummaryIndex = 1,
            StartLoc = loc,
            TargetLoc = tagertLocId,
            MaterialId = prodSku.MaterialId,
            PlanCount = 1,
            RealCount = 0,
            UseFlag = 1
        };
        var OutOrderSummarys = new List<POWmsOutOrderSummary>() { OutOrderSummary };
        var result = _WmsOutOrderSummary.AddOutOrderSummaryListByLoc(OutOrderSummarys) == 0 ? "创建失败" : "创建成功";
        return result;
    }
    /// <summary>
    /// 根据多个库位创建出库单
    /// </summary>
    /// <param name="parm"></param>
    /// <returns></returns>
    public string CreateOutOrders_bak(CreateOrderParms parm)
    {
        var result = "";
        foreach (var loc in parm.locs)
        {
            result = CheckLoc(loc);
            if (!string.IsNullOrWhiteSpace(result))
            {
                return result;
            }
        }
        var locinfos = _RcsLocation.GetAllLocations().Where(t => parm.locs.Contains(t.Id.GetValueOrDefault())).ToList();
        var locinfoGroups = locinfos.GroupBy(t => new { t.GroupId })
            .Select(t => new
            {
                GroupId = t.Key.GroupId.Value,
                Count = t.Count(),
                LocInfos = t.OrderBy(x => x.GroupIndex).ToList()
            }).ToList();
        var locinfoDoubleGroups = locinfoGroups.Where(t => t.Count == 2).ToList();
        locinfoDoubleGroups.ForEach(group =>
        {
            CreateOrderMaterAndSummary(group.LocInfos, "");
        });
        var locHold = _WcsEquipLocHold.GetEquipLocHolds();
        var doubleGroups = locinfoDoubleGroups.Select(t => t.GroupId).ToList();
        var locinfoSingle = locinfos
            //多个堆垛机货位
            /*.Join(locHold, f => f.Id, s => s.LocId, (f, s) =>new { 
            LocId=f.IdCreateOutOrders
            GroupId=f.GroupId,
            LocCode=f.LocCode,
            CrnId =s.EquipId
           })*/
            .Where(t => !doubleGroups.Contains(t.GroupId.GetValueOrDefault())).OrderBy(t => t.LocCode).ToList();

        locinfoSingle.ForEach(loc =>
       {
           var loc2 = locinfoSingle.Where(t => t.Id != loc.Id).FirstOrDefault();
           var locList = new List<PORcsLocation>();
           locList.Add(loc);
           if (loc2 != null)
           {
               locList.Add(loc2);
               locinfoSingle.Remove(loc2);
           }
           CreateOrderMaterAndSummary(locList.OrderBy(t => t.GroupIndex).ToList(), "");
       });
        if (string.IsNullOrWhiteSpace(result))
        {
            result = "成功";
        }
        return result;
    }
    [OperationLog("出库")]
    public string CreateOutOrders(CreateOrderParms parm, long userId, string userName, string clientHost)
    {
        if (parm.locs is null)
        {
            return "未接收到库位号";
        }
        var result = "";
        // 手工出库数量
        var locMasterIds = _WmsOutOrderMaster.GetOutOrderMasterList().Where(t => t.OrderType == (int)EnumCodeOutOrderType.WarehouseLocation).Select(t => t.Id).ToList();
        // 生成任务数
        var taskCount = _Task.GetTaskList().Where(t => locMasterIds.Contains(t.MasterId)).Count();
        // 限制数量
        var locOutCount = Convert.ToInt32(_WmsSetting.GetWmsSettings().Where(t => t.Code == ConstFields.LocaltionOutCount).FirstOrDefault()?.Value ?? "0");
        if (taskCount + parm.locs.Count > locOutCount)
        {
            return "异常出库数量超出最大数";
        }


        foreach (var loc in parm.locs)
        {
            result = CheckLoc(loc);
            if (!string.IsNullOrWhiteSpace(result))
            {
                return result;
            }
        }
        var locinfos = _RcsLocation.GetLocations().Where(t => parm.locs.Contains(t.Id.GetValueOrDefault())).ToList();
        CreateOrderMaterAndSummary(locinfos.OrderBy(t => t.GroupIndex).ToList(), parm.outType);
        if (string.IsNullOrWhiteSpace(result))
        {
            result = "成功";
        }
        return result;
    }
    private string CreateOrderMaterAndSummary(List<PORcsLocation> locs, string type)
    {
        var masterId = _WmsOutOrderMaster.AddOutOrderMaster((int)EnumCodeOutOrderType.WarehouseLocation, type);
        var OutOrderSummarys = new List<POWmsOutOrderSummary>();
        var index = 1;
        foreach (var loc in locs)
        {

            var locSku = _WcsLocSku.GetWcsLocSkuByLocId(loc.Id);
            var prodSku = _ProdSku.GetProdSkuById(locSku.SkuId);
            var equip = _WcsEquipLocHold.GetEquipLocHolds().Where(t => t.LocId == loc.Id).FirstOrDefault();

            // 立库异常口
            var tagertLocId = _WcsAsrsCrnAbnormalOutPut.GetAsrsCrnAbnormalOutPutByCrnId(equip.EquipId.GetValueOrDefault())?.OutputLoc1 ?? 0;
            if (type == "2")
            {
                // 线体异常口
                var crnOut = _WcsAsrsCrnOutPut.GetAsrsCrnOutPutByCrnId(equip.EquipId.GetValueOrDefault());
                tagertLocId = _WcsNetAbnormal.GetAbnormalIdByStartLoc(crnOut.OutputLoc1.GetValueOrDefault());
            }
            var OutOrderSummary = new POWmsOutOrderSummary
            {
                MasterId = masterId,
                SummaryIndex = index,
                StartLoc = loc.Id,
                TargetLoc = tagertLocId,
                MaterialId = prodSku.MaterialId,
                PlanCount = 1,
                RealCount = 0,
                UseFlag = 1,
                RemarkMemo = type == "2" ? "线体手工出库" : "立库手工出库",
            };
            Client.Log(new Log { Data = $"开始货位编号为： {loc.Id},订单主表Id为：{OutOrderSummary.MaterialId}" });
            OutOrderSummarys.Add(OutOrderSummary);

            index++;
        }


        var result = _WmsOutOrderSummary.AddOutOrderSummaryListByLoc(OutOrderSummarys) == 0 ? "E" : "S";
        return result;
    }
    private string CheckLoc(long loc)
    {
        var result = "";
        if (loc == 0)
        {
            result = $"{loc}未找到库位";
            return result;
        }
        var locInfo = _RcsLocation.GetLocationById(loc);
        //未查询到货位信息
        if (locInfo == null)
        {
            result = $"{loc}未找到库位";
            return result;
        }
        if (locInfo.LocHasSku != 1)
        {

            result = $"{locInfo.LocName}该库位没有库存";
            return result;
        }

        //查询库位是否存在SKU
        var locSku = _WcsLocSku.GetWcsLocSkuByLocId(loc);
        if (locSku == null)
        {
            result = $"{locInfo.LocName}未找到相应的SKU信息";
            return result;
        }
        var prodSku = _ProdSku.GetProdSkuById(locSku.SkuId);
        if (prodSku == null)
        {

            result = $"{locInfo.LocName}未找到相应的SKU信息";
            return result;
        }

        //验证当前库位是否存在待执行或者执行中的指令
        var locCmd = _TaskCmd.GetTaskCmdByStartLocId(loc);
        if (locCmd.Count != 0)
        {
            result = $"{locInfo.LocName}该库位存在正在执行的指令";
            return result;
        }
        var equip = _WcsEquipLocHold.GetEquipLocHolds().Where(t => t.LocId == loc).FirstOrDefault();
        if (equip == null)
        {

            result = $"{locInfo.LocName}未找到该库位的堆垛机信息";
            return result;
        }
        //获取异常库位信息
        //var tagertLocId = _WcsNetAbnormal.GetAbnormalIdByStartLoc(equip.EquipId.GetValueOrDefault());
        //if (tagertLocId == 0)
        //{
        //    result = $"{locInfo.LocName}未找到该库位的异常库位信息";
        //    return result;
        //}
        var summaryNum = _WmsOutOrderSummary.GetOrderSummaryList().Where(t => t.StartLoc == loc).Count();
        if (summaryNum > 0)
        {
            result = $"{locInfo.LocName}该库位已创建出库单";
            return result;
        }
        return result;
    }
    public List<OrderMastersBean> GetOutOrder(OrderParm parm)
    {

        var summaryMasters = _WmsOutOrderMaster.GetOutOrderMasterSummaryList()
            .Select(t => new OrderMastersBean
            {
                OrderId = t.MasterId,
                OrderCode = t.OrderCode,
                OrderType = t.OrderType,
                TargetLoc = t.TargetLoc,
                OrderStatus = t.OrderStatus,
                OrderPriority = t.OrderPriority,
                CreateTime = t.CreateTime,
                RealCount = t.RealCount,
                PlanCount = t.PlanCount,
                Remark = t.Remark,
            }).ToList();
        if (!string.IsNullOrWhiteSpace(parm.OrderCode))
        {
            summaryMasters = summaryMasters.Where(t => t.OrderCode.Contains(parm.OrderCode)).ToList();
        }
        var targetLocs = summaryMasters.Select(t => t.TargetLoc).ToList();
        var locs = _RcsLocation.GetLocationsByLocIds(targetLocs);

        summaryMasters = summaryMasters.Join(locs, f => f.TargetLoc, s => s.Id, (f, s) => new OrderMastersBean
        {
            OrderId = f.OrderId,
            OrderCode = f.OrderCode,
            OrderType = f.OrderType,
            TargetLoc = f.TargetLoc,
            OrderStatus = f.OrderStatus,
            OrderPriority = f.OrderPriority,
            CreateTime = f.CreateTime,
            TargetLocName = s.LocName,
            TargetLocCode = s.LocCode,
            RealCount = f.RealCount,
            PlanCount = f.PlanCount,
            Remark = f.Remark,
        }).ToList();

        if (!string.IsNullOrWhiteSpace(parm.OrderType))
        {
            summaryMasters = summaryMasters.Where(t => t.OrderType == Convert.ToInt32(parm.OrderType)).ToList();
        }
        if (!string.IsNullOrWhiteSpace(parm.TargetLocCode))
        {
            summaryMasters = summaryMasters.Where(t => t.TargetLocCode.Contains(parm.TargetLocCode)).ToList();
        }
        if (!string.IsNullOrWhiteSpace(parm.TargetLocName))
        {
            summaryMasters = summaryMasters.Where(t => t.TargetLocName.Contains(parm.TargetLocName)).ToList();
        }


        summaryMasters.ForEach(item =>
        {
            switch (item.OrderType)
            {
                case (int)EnumCodeOutOrderType.RequesMaterial:
                    item.OrderTypeDesc = "硫化请料";
                    break;
                case (int)EnumCodeOutOrderType.GeneralDelivery:
                    item.OrderTypeDesc = "普通出库";
                    break;
                case (int)EnumCodeOutOrderType.WarehouseLocation:
                    item.OrderTypeDesc = "库位出库";
                    break;
                case (int)EnumCodeOutOrderType.WarehouseProductCode:
                    item.OrderTypeDesc = "条码出库";
                    break;
                case (int)EnumCodeOutOrderType.WarehouseMaterial:
                    item.OrderTypeDesc = "规格出库";
                    break;
                default:
                    item.OrderTypeDesc = "超期出库";
                    break;

            }
            switch (item.OrderStatus)
            {
                case (int)EnumCodeOutOrderStatus.Create:
                    item.OrderStatusDesc = "创建";
                    break;
                case (int)EnumCodeOutOrderStatus.Execute:
                    item.OrderStatusDesc = "执行";
                    break;
                case (int)EnumCodeOutOrderStatus.Stop:
                    item.OrderStatusDesc = "暂定";
                    break;
                default:
                    item.OrderStatusDesc = "移栽";
                    break;

            }
        });
        return summaryMasters;

    }


    public List<CuringOutOrderBean> GetCuringOutOrderDetails(CuringOutOrderParm parm)
    {

        var result = _MesCuringRequestMaterial.GetCuringOutOrderDetails();
        if (!string.IsNullOrWhiteSpace(parm.MaterialCode))
        {
            result = result.Where(t => t.MaterialCode.Contains(parm.MaterialCode)).ToList();
        }
        if (!string.IsNullOrWhiteSpace(parm.OrderStatus))
        {
            result = result.Where(t => t.OrderStatus.Contains(parm.OrderStatus)).ToList();
        }
        if (!string.IsNullOrWhiteSpace(parm.EquipNo))
        {
            result = result.Where(t => t.EquipNo.Contains(parm.EquipNo)).ToList();
        }
        return result;
    }


    [Obsolete("暂未启用", true)]
    public int UpdateOrderStatus(OrderStatusParm parm)
    {
        var master = _WmsOutOrderMaster.GetOutOrderMasterById(parm.OrderId);
        if (master == null)
        {
            return 0;
        }
        if (parm.Status == (int)EnumCodeOutOrderStatus.Stop && master.OrderStatus != (int)EnumCodeOutOrderStatus.Create)
        {
            return 1;
        }
        if (parm.Status == (int)EnumCodeOutOrderStatus.StartUp && master.OrderStatus != (int)EnumCodeOutOrderStatus.Stop)
        {
            return 1;
        }
        var status = (parm.Status == (int)EnumCodeOutOrderStatus.Stop) ? (int)EnumCodeOutOrderStatus.Stop : (int)EnumCodeOutOrderStatus.Create;
        return _WmsOutOrderMaster.UpdateMasterStatus(master.Id.GetValueOrDefault(), status);
    }

    public int GetOutOrderDetails(long summaryId)
    {
        if (summaryId == 0)
        {
            return 0;
        }
        var summary = _WmsOutOrderSummary.GetOutOrderSummaryById(summaryId);

        var task = _Task.GetTasksBySummaryId(summaryId);
        //task ?? _BakWcsTask.GetBakTasksBySummaryId(summaryId); 



        //var scanIds = _RcsEquip.GetEquips().Where(t => t.EquipType == 8).Select(t => t.Id).ToList();
        //var scanLocs = _WcsEquipLoc.GetEquipLocList().Where(t => scanIds.Contains(t.EquipId)).Select(t => t.LocId).ToList();


        if (task == null)
        {
            return 1;
        }
        var taskCmd = _TaskCmd.GetTaskCmdByTaskNo(task.TaskNo.GetValueOrDefault());

        if (taskCmd == null)
        {
            return 1;
        }
        if (taskCmd.CmdType == (int)EnumTaskType.Exwarehouse)
        {
            return 3;
        }
        else if (taskCmd.CmdType == (int)EnumTaskType.Transportation)
        {
            return 4;
        }
        else
        {
            return 6;
        }



    }

    public orderMasterBean GetOutOrderDetailsByMasterId(long masterId)
    {

        var master = _WmsOutOrderMaster.GetOutOrderMasterById(masterId);
        var locs = _RcsLocation.GetAllLocations().Where(t => t.LocType == 7);
        var materialList = _ProdMaterial.GetMaterialList();
        var summaryList = _WmsOutOrderMaster.GetOutOrderSummaryList().Where(t => t.MasterId == masterId).ToList();

        var summaryLoc = summaryList.Join(locs, f => f.TargetLoc, s => s.Id, (f, s) => new
        {
            loc = s,
            summary = f
        }).Join(materialList, f => f.summary.MaterialId, s => s.Id, (f, s) => new
        {

            summary = f.summary,
            loc = f.loc,
            material = s,
        });

        var summaryLeft = summaryLoc.Where(t => t.loc.GroupIndex == 2).FirstOrDefault();
        var summaryRight = summaryLoc.Where(t => t.loc.GroupIndex == 1).FirstOrDefault();

        long leftSummaryId = 0;
        long rightSummaryId = 0;
        string leftMaterialCode = string.Empty;
        string rightMaterialCode = string.Empty;

        if (summaryLeft is not null)
        {
            leftSummaryId = summaryLeft.summary.Id ?? 0;
            leftMaterialCode = summaryLeft.material.MaterialCode;
        }
        if (summaryRight is not null)
        {
            rightSummaryId = summaryRight.summary.Id ?? 0;
            rightMaterialCode = summaryRight.material.MaterialCode;
        }

        orderMasterBean masterBean = new()
        {
            MasterId = master.Id ?? 0,
            LeftSummaryId = leftSummaryId,
            LeftMaterialCode = leftMaterialCode,
            RightSummaryId = rightSummaryId,
            RightMaterialCode = rightMaterialCode,
        };
        return masterBean;

    }


    /// <summary>
    /// 获取所有正在执行的出库订单信息并整合为看板数据
    /// </summary>
    /// <returns></returns>
    public List<OutOrderKanBan> GetOutOrderKanBans()
    {
        var db = Db.Default;
        try
        {
            var locs = db.RcsLocations.ToList();
            List<OutOrderKanBan> result = new List<OutOrderKanBan>();
            //1 查询所有出库订单
            var allOutOrderMasters = db.WmsOutOrderMasters.ToList();

            //根据出库主表组合数据
            foreach (var item in allOutOrderMasters)
            {
                OutOrderKanBan outOrderKanBan = new OutOrderKanBan();
                outOrderKanBan.OutOrderMaserId = item.Id.GetValueOrDefault();
                var summarys = GetOutOrderSummary(item.Id.GetValueOrDefault(), db, locs);
                int create = 0;
                foreach (var suItem in summarys)
                {
                    if (suItem.IsCreateTask == 1)
                    {
                        create = 1;//主数据标记以创建任务  排序用
                    }
                }
                outOrderKanBan.Index = create;
                outOrderKanBan.Summarys = summarys;
                outOrderKanBan.MasterCreateTime = item.CreateTime.GetValueOrDefault();
                result.Add(outOrderKanBan);
            }
            result = result.OrderBy(O => O.MasterCreateTime).ToList();
            return result.OrderByDescending(O => O.Index).ToList();
        }
        catch (Exception)
        {
            return null;
        }
    }


    /// <summary>
    /// 根据出库主表ID获取子表数据
    /// </summary>
    /// <returns></returns>
    public List<OutOrderSummaryKanBan> GetOutOrderSummary(long masterId, Db db, List<PORcsLocation> locs)
    {
        List<OutOrderSummaryKanBan> result = new List<OutOrderSummaryKanBan>();
        var summarys = db.WmsOutOrderSummarys.Where(T => T.MasterId == masterId).ToList();
        foreach (var item in summarys)
        {

            OutOrderSummaryKanBan outOrderSummaryKanBan = new OutOrderSummaryKanBan();
            outOrderSummaryKanBan.OutOrderSummaryId = item.Id.GetValueOrDefault();
            //查询出库轮胎规格信息
            var material = db.ProdMaterials.Where(T => T.Id == item.MaterialId).FirstOrDefault();
            if (material != null)
            {
                outOrderSummaryKanBan.Spec = material.Spec;
            }
            //查询目的地信息
            var tarLoc = locs.Where(T => T.Id == item.TargetLoc).FirstOrDefault();
            if (tarLoc != null)
            {
                outOrderSummaryKanBan.TargetLoc = tarLoc.LocName;
                //从名称中分离出左右模信息
                try
                {
                    string lOrR = tarLoc.LocName.Split('机')[1].Substring(0, 1);
                    outOrderSummaryKanBan.LeftOrRight = Convert.ToInt32(lOrR);
                }
                catch (Exception ex)
                {
                    //屏蔽可能的报错
                }
            }


            //查询任务信息
            var task = db.WcsTasks.Where(T => T.SummaryId == item.Id).FirstOrDefault();
            if (task != null)
            {
                outOrderSummaryKanBan.IsCreateTask = 1;
                //根据任务SKU查询条码信息
                var sku = db.ProdSkuProducts.Join(db.ProdProducts, a => a.ProductId, b => b.Id, (a, b) => new { sku = a, product = b }).Where(T => T.sku.SkuId == task.SkuId).FirstOrDefault();
                if (sku != null)
                {
                    outOrderSummaryKanBan.Barcode = sku.product.ProductCode;
                }
                outOrderSummaryKanBan.TaskId = task.Id.GetValueOrDefault();
                //任务生成时间
                outOrderSummaryKanBan.OutRealTime = task.CreateTime.GetValueOrDefault();
                outOrderSummaryKanBan.TaskSn = task.TaskNo.GetValueOrDefault();
                //根据任务信息查条码
                var prodSku = db.ProdSkuProducts.Where(T => T.SkuId == task.SkuId).FirstOrDefault();
                if (prodSku != null)
                {
                    //查条码
                    var product = db.ProdProducts.Where(T => T.Id == prodSku.ProductId).FirstOrDefault();
                    if (product != null)
                    {
                        outOrderSummaryKanBan.Barcode = product.ProductCode;
                    }
                }
                //查询出库位置
                var staLoc = locs.Where(T => T.Id == task.StartLoc).FirstOrDefault();
                if (staLoc != null)
                {
                    outOrderSummaryKanBan.StartLoc = staLoc.LocName;
                }

            }
            else
            {
                outOrderSummaryKanBan.IsCreateTask = 0;
            }
            result.Add(outOrderSummaryKanBan);
        }
        return result;
    }

    /// <summary>
    /// 根据任务获取指令集
    /// </summary>
    /// <returns></returns>
    public List<OutOrderSchedule> GetOutOrderSchedules(long taskId)
    {
        List<OutOrderSchedule> result = new List<OutOrderSchedule>();
        var db = Db.Default;

        //已完成的
        var taskCmd = db.BakWcsTaskCmds.Where(T => T.TaskId == taskId).OrderBy(O => O.CreateTime).ToList();
        int index = 0;
        foreach (var item in taskCmd)
        {
            OutOrderSchedule outOrderSchedule = new OutOrderSchedule();
            outOrderSchedule.CmdId = item.Id.GetValueOrDefault();
            outOrderSchedule.IsOver = 1;
            outOrderSchedule.Index = index;
            outOrderSchedule.CreateTime = item.CreateTime.GetValueOrDefault();
            outOrderSchedule.OverTime = item.BackTime.GetValueOrDefault();
            index++;
            result.Add(outOrderSchedule);
        }
        //未完成的
        var taskCmdNo = db.WcsTaskCmds.Where(T => T.TaskId == taskId).OrderBy(O => O.CreateTime).ToList();
        foreach (var item in taskCmdNo)
        {
            OutOrderSchedule outOrderSchedule = new OutOrderSchedule();
            outOrderSchedule.CmdId = item.Id.GetValueOrDefault();
            outOrderSchedule.IsOver = 0;
            outOrderSchedule.Index = index;
            outOrderSchedule.CreateTime = item.CreateTime.GetValueOrDefault();
            index++;
            result.Add(outOrderSchedule);
        }
        return result;

    }


    /// <summary>
    /// 根据指令id获取指令明细
    /// </summary>
    /// <param name="cmdId"></param>
    /// <param name="over"></param>
    /// <returns></returns>
    public string GetTaskCmd(long cmdId, int over)
    {
        var db = Db.Default;
        {
            if (over == 1)
            {
                //var result = db.BakWcsTaskCmds.Where(T => T.Id == cmdId).FirstOrDefault();

                var result = db.BakWcsTaskCmds.Join(db.RcsLocations, f => f.StartLoc, s => s.Id, (f, s) => new
                {
                    f.Id,
                    f.TaskId,
                    f.TaskType,
                    f.TaskNo,
                    f.CreateTime,
                    f.CmdType,
                    f.CmdStatus,
                    f.CurrentLoc,
                    f.TargetLoc,
                    StartLocName = s.LocName,
                }).Where(t => t.Id == cmdId).Join(db.RcsLocations, f => f.CurrentLoc, s => s.Id, (f, s) => new
                {
                    f.Id,
                    f.TaskId,
                    f.TaskType,
                    f.TaskNo,
                    f.CreateTime,
                    f.CmdType,
                    f.CmdStatus,
                    f.TargetLoc,
                    f.StartLocName,
                    CurrentLocName = s.LocName,
                }).Join(db.RcsLocations, f => f.TargetLoc, s => s.Id, (f, s) => new
                {
                    f.Id,
                    f.TaskId,
                    f.TaskType,
                    f.TaskNo,
                    f.CreateTime,
                    CmdType = GetTaskTypeName(f.CmdType ?? 0),
                    CmdStatus = GetTaskStatusName(f.CmdStatus ?? 0),
                    TargetLoc = s.LocName,
                    CurrentLoc = f.CurrentLocName,
                    StartLoc = f.StartLocName,
                }).ToList();

                if (result != null)
                {
                    return result.ToJson();
                }
            }
            else
            {
                //var result = db.WcsTaskCmds.Where(T => T.Id == cmdId).FirstOrDefault();


                var result = db.WcsTaskCmds.Join(db.RcsLocations, f => f.StartLoc, s => s.Id, (f, s) => new
                {
                    f.Id,
                    f.TaskId,
                    f.TaskType,
                    f.TaskNo,
                    f.CreateTime,
                    f.CmdType,
                    f.CmdStatus,
                    f.CurrentLoc,
                    f.TargetLoc,
                    StartLocName = s.LocName,
                }).Where(t => t.Id == cmdId).Join(db.RcsLocations, f => f.CurrentLoc, s => s.Id, (f, s) => new
                {
                    f.Id,
                    f.TaskId,
                    f.TaskType,
                    f.TaskNo,
                    f.CreateTime,
                    f.CmdType,
                    f.CmdStatus,
                    f.TargetLoc,
                    CurrentLocName = s.LocName,
                    f.StartLocName,
                }).Join(db.RcsLocations, f => f.TargetLoc, s => s.Id, (f, s) => new
                {
                    f.Id,
                    f.TaskId,
                    f.TaskType,
                    f.TaskNo,
                    f.CreateTime,
                    CmdType = GetTaskTypeName(f.CmdType ?? 0),
                    CmdStatus = GetTaskStatusName(f.CmdStatus ?? 0),
                    TargetLoc = s.LocName,
                    CurrentLoc = f.CurrentLocName,
                    StartLoc = f.StartLocName,
                }).ToList();

                if (result != null)
                {
                    return result.ToJson();
                }
            }
            return "";
        }

    }


    static string GetTaskTypeName(int type)
    {
        var name = "";
        switch (type)
        {
            case (int)EnumTaskType.Warehousing:
                name = "入库任务";
                break;
            case (int)EnumTaskType.Exwarehouse:
                name = "出库任务";
                break;
            case (int)EnumTaskType.Transportation:
                name = "输送任务";
                break;
            case (int)EnumTaskType.EMS:
                name = "EMS任务";
                break;
            case (int)EnumTaskType.Abnormal:
                name = "异常任务";
                break;
        }
        return name;

    }

    static string GetTaskStatusName(int status)
    {
        var name = "";
        switch (status)
        {
            case (int)EnumTaskCmdStatus.Executable:
                name = "可执行";
                break;
            case (int)EnumTaskCmdStatus.Executed:
                name = "已执行";
                break;
            case (int)EnumTaskCmdStatus.Finish:
                name = "已完成";
                break;
        }
        return name;

    }




}


